package com.gitee.fanx.retty.demo.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author fanhang
 */
public class WebResult<T> {

	private Integer code;

	private String message;

	private T data;

	public WebResult() {
	}

	public WebResult(Integer code, String message, T data) {
		this.code = code;
		this.message = message;
		this.data = data;
	}

	public static WebResult<?> success() {
		return success(null);
	}

	public static <T> WebResult<T> success(T data) {
		return new WebResult<T>(200, null, data);
	}

	/**
	 * 失败响应结果
	 * @param message 消息
	 * @return 响应结果
	 */
	public static WebResult<?> fail(String message) {
		return new WebResult<Object>(1000, message, null);
	}

	/**
	 * 失败响应结果
	 * @param resultCode 状态码枚举
	 * @return 响应结果
	 */
	public static WebResult<?> fail(int resultCode, final String message) {
		return new WebResult<Object>(resultCode, message, null);
	}

	@Override
	public String toString() {
		try {
			return new ObjectMapper().writeValueAsString(this);
		}
		catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	public Integer getCode() {
		return this.code;
	}

	public WebResult<T> setCode(final Integer code) {
		this.code = code;
		return this;
	}

	public String getMessage() {
		return this.message;
	}

	public WebResult<T> setMessage(final String message) {
		this.message = message;
		return this;
	}

	public T getData() {
		return this.data;
	}

	public WebResult<T> setData(final T data) {
		this.data = data;
		return this;
	}

}
